﻿using System;
using System.Collections.Generic;
using System.Data.Entity;

using System.Linq;
using System.Web.Mvc;

using PagedList;
using SIG.Service;
using SIG.Model;
using SIG.Basic.Helper;

using SIG.Model.ViewModel.Back;
using AutoMapper;
using SIG.WebUI.Areas.Admin.Models;
using SIG.Model.DTO;
using SIG.Model.Extensions;

namespace SIG.WebUI.Areas.Admin.Controllers
{
  
    [Authorize]
    //[InitializeSimpleMembership]
    public class ProductController : AdminController
    {
      
         private readonly ICategoryService _categoryService;
         private readonly IProductService _productService;
         private readonly IProductPhotoService _productPhotoService;
        private readonly IPageMetaService _pageMetaService;

         public ProductController(ICategoryService categoryService, IProductService productService, IProductPhotoService productPhotoService, IPageMetaService pageMetaService)
        {
            _categoryService = categoryService;
            _productService = productService;
            _productPhotoService = productPhotoService;
            _pageMetaService = pageMetaService;

            AjaxResult = new Model.ViewModel.AjaxResultVM();
        }

        #region 产品分类
        

        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <returns></returns>
         public List<SelectListItem> GetCategoryList()
         {
             var OptGroups  = _categoryService.GetAllCategories(ModelType.PRODUCT).ToList();        
            //   lCategories.Insert(0, new SelectListItem { Text = "--按分类过滤--", Value = "" });
             return (from category in OptGroups
                 
                 select new SelectListItem
                 {
                     Text = category.Title,
                     Value = category.Id.ToString()
                     // Selected = (blogId == blog.Id)
                 }).ToList();
         }
        // 二级下拉
        public List<SelectListItem> GetCategoryListWithParent()
        {
            var OptGroups = _categoryService.GetAllCategories(ModelType.PRODUCT).Select(c => new SelectListGroup { Name = c.Title }).ToList();
            var categories = _categoryService.GetChildCategoriesWithParent(ModelType.PRODUCT);
            //   lCategories.Insert(0, new SelectListItem { Text = "--按分类过滤--", Value = "" });

            return (from category in categories
                    let parId = category.ParentId.ToString()
                    select new SelectListItem
                    {
                        Text = category.Title,
                        Value = category.Id.ToString(),
                        Group = OptGroups.FirstOrDefault(o => o.Name == category.ParentCategoryTitle)
                        // Selected = (blogId == blog.Id)
                    }).ToList();
        }

        //单级下拉
        public List<SelectListItem> GetCategoryList(int catId)
         {
             var OptGroups = _categoryService.GetAllCategories(ModelType.PRODUCT).ToList();            
             List<SelectListItem> lCategories = new List<SelectListItem>();
             foreach (var category in OptGroups)
             {            
                 var sli = new SelectListItem
                 {
                     Text = category.Title,
                     Value = category.Id.ToString(),                 
                     Selected = (catId == category.Id)
                 };

                 lCategories.Add(sli);

             }
             lCategories.Insert(0, new SelectListItem { Text = "--按分类过滤--", Value = "" });

             return lCategories;
         }

        // 带组下拉（二级）
        public List<SelectListItem> GetCategoryListWidthParent(int catId)
        {
            var OptGroups = _categoryService.GetAllCategories(ModelType.PRODUCT).Select(c => new SelectListGroup { Name = c.Title }).ToList();
            var categories = _categoryService.GetChildCategoriesWithParent(ModelType.PRODUCT);
            List<SelectListItem> lCategories = new List<SelectListItem>();
            foreach (var category in categories)
            {
                var parId = category.ParentId.ToString();
                var sli = new SelectListItem
                {
                    Text = category.Title,
                    Value = category.Id.ToString(),
                    Group = OptGroups.FirstOrDefault(o => o.Name == category.ParentCategoryTitle),
                    Selected = (catId == category.Id)
                };

                lCategories.Add(sli);

            }
            lCategories.Insert(0, new SelectListItem { Text = "--按分类过滤--", Value = "" });

            return lCategories;
        }

        #endregion

        #region  产品

        [Authorize(Roles = "创始人,管理员")]
         public ActionResult Index(int? page, int? catId)
         {
             var productsVM = new ProductListVM();

             productsVM.CatId = catId ?? 0;
             productsVM.PageIndex = (page ?? 1) - 1;
             productsVM.PageSize = Site.Settings.Product.PageSize;

             productsVM.Products = _productService.SearchProducts(productsVM.PageIndex, productsVM.PageSize, productsVM.CatId);

             productsVM.TotalCount = _productService.SearchProductsCount(productsVM.CatId);
             productsVM.Categories = GetCategoryList(productsVM.CatId);

             var prosAsIPagedList = new StaticPagedList<Product>(productsVM.Products, productsVM.PageIndex + 1, productsVM.PageSize, productsVM.TotalCount);
             ViewBag.OnePageOfProducts = prosAsIPagedList;

             return View(productsVM);

            
             //int PageSize = Site.Settings.PageSize;

             //ProductListVM productList = new ProductListVM
             //{
             //    Products = _productService.GetAll().Include(p=>p.Categories).OrderByDescending(s => s.AddedDate)
             //         .Skip((page - 1) * PageSize)
             //         .Take(PageSize),
             //    PagingInfo = new PagingInfo
             //    {
             //        CurrentPage = page,
             //        ItemsPerPage = PageSize,
             //        TotalItems = _productService.GetAll().Count()
             //    }
             //};
             //return View(productList);
         }



          [Authorize(Roles = "创始人,管理员")]
         public ActionResult AddProduct()
         {
            ProductPageMetaDTO product = new ProductPageMetaDTO();
             product.Active = true;

          
             ViewBag.Categories = GetCategoryList();
             return View("AddProduct", product);
         }


         [HttpPost]
          [Authorize(Roles = "创始人,管理员")]
         public JsonResult AddProduct(ProductPageMetaDTO product)
         {
           

            if (!ModelState.IsValid)
            {
                var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage));

                AjaxResult.SetError(message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }

            try
            {
                var newProduct = Mapper.Map<ProductPageMetaDTO, Product>(product);

              
                    var lCategories = (from c in _productService.GetCategories()
                                       where newProduct.PostCategoryIds.Contains(c.Id.ToString())
                                       select c).ToList();

                    newProduct.Categories = lCategories;
             
              
                //product.CategoryIds = string.Join(",", product.PostCategoryIds);

                _productService.Create(newProduct);

                if(!string.IsNullOrEmpty(product.Keywords) || !string.IsNullOrEmpty(product.SEODescription))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newProduct.Id,
                        Keyword = product.Keywords,
                        Description = product.SEODescription,
                        ModelType = ModelType.PRODUCT
                    };
                    _pageMetaService.Create(pageMeta);
                }

                AjaxResult.Message = String.Format(Site.AlertCreateSuccess, Site.Settings.Product.SetName);
                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AjaxResult.SetError(er.Message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);
            }



        }

          [Authorize(Roles = "创始人,管理员")]
         public ActionResult EditProduct(int id)
         {
            

             var vProduct = _productService.GetProductByIdWithCategories(id);
             if (vProduct != null)
             {
                if(vProduct.Categories.Count>0 )
                  vProduct.PostCategoryIds = vProduct.Categories.Select(c=>c.Id.ToString()).ToArray();

                var editProduct = Mapper.Map<Product, ProductPageMetaDTO>(vProduct);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.PRODUCT, editProduct.Id);
                if (pageMeta != null)
                {
                    editProduct.Keywords = pageMeta.Keyword;
                    editProduct.SEODescription = pageMeta.Description;
                }

                ViewBag.Categories = GetCategoryList();
              

                return View(editProduct);
             }             

             return View("NotFound");
         }


        
         [HttpPost]
         [ValidateInput(false)]
         [Authorize(Roles = "创始人,管理员")]

         public JsonResult EditProduct(ProductPageMetaDTO product)
         {
        

            if (!ModelState.IsValid)
            {
                var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage));

                AjaxResult.SetError(message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }



            try
            {
                var editProduct = Mapper.Map<ProductPageMetaDTO, Product>(product);

                

                //product.CategoryIds = string.Join(",", product.PostCategoryIds);

                _productService.UpdateProductWithCategory(editProduct);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.PRODUCT, editProduct.Id);
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(product.Keywords) || !string.IsNullOrEmpty(product.SEODescription))
                {

                    pageMeta.ObjectId = editProduct.Id;
                    pageMeta.Keyword = product.Keywords;
                    pageMeta.Description = product.SEODescription;
                    pageMeta.ModelType = ModelType.PRODUCT;
                 
                    if(pageMeta.Id >0 )
                    {
                        _pageMetaService.Update(pageMeta);
                    }                       
                    else
                    {                    
                        _pageMetaService.Create(pageMeta);
                    }
                }

                AjaxResult.Message = String.Format(Site.AlertUpdateSuccess, Site.Settings.Product.SetName);
                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AjaxResult.SetError(er.Message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);
            }




            //_productService.UpdateProductWithCategory(product);
            //     return Json(true, JsonRequestBehavior.DenyGet);

            
            

         }

            [HttpPut]
         public JsonResult RecommendProduct(int id)
         {

             Product vProduct = _productService.GetById(id);

             try
             {
                 if (vProduct != null)
                 {
                     vProduct.Recommend = !vProduct.Recommend;

                     _productService.Update(vProduct);
                    // _unit.SaveChanges();
                     
                 }
             }
             catch (Exception ex)
             {
                 return Json(false, JsonRequestBehavior.DenyGet);
             }

             return Json(true, JsonRequestBehavior.DenyGet);
             

         }


         // DELETE: /User/DeleteSite
         [HttpDelete]
         public JsonResult DeleteProduct(int id)
         {

             Product vProduct = _productService.GetById(id);

             if (vProduct != null)
             {
                 
                 _productService.Delete(vProduct);
  
                 return Json(true, JsonRequestBehavior.DenyGet);
             }

             return Json(false, JsonRequestBehavior.DenyGet);
         }

        #endregion

        #region 产品图片
         //
         // GET: /Admin/Product/Photos
         [Authorize(Roles = "创始人,管理员")]
         public ActionResult Photos(int productId=0)
         {
             if (productId <= 0) return RedirectToAction("Index");

             ViewBag.Photos = _productPhotoService.GetPhotos(productId);
             var photo = new ProductPhoto
             {
                 ProductId = productId
             };
          
             return View(photo);
         }

         [HttpPost]
         [Authorize(Roles = "创始人,管理员")]
         public JsonResult AddPhoto(ProductPhoto photo)
         {
             //photo.AddedDate = DateTime.Now;
             //photo.AddedBy = Site.CurrentUserName;

             if (ModelState.IsValid)
             {
                 _productPhotoService.Create(photo);
                 return Json(true, JsonRequestBehavior.DenyGet);

             }
             
             return Json(false, JsonRequestBehavior.DenyGet);
            
             //   return RedirectToAction("Index");

         }

         // DELETE: /Product/DeletePhoto
         [HttpDelete]
         [Authorize(Roles = "创始人,管理员")]
         public JsonResult DeletePhoto(int id)
         {

             var photo = _productPhotoService.GetById(id);

             if (photo == null) return Json(false, JsonRequestBehavior.DenyGet);

             _productPhotoService.Delete(photo);
             return Json(true, JsonRequestBehavior.DenyGet);
         }


        #endregion
    }
}
